<template>
  <div class="search">
    <div class="header app-header">
      <form action="/">
        <van-search
          ref="searchRef"
          v-model="searchVal"
          show-action
          autofocus
          shape="round"
          placeholder="请输入搜索关键词"
          @search="onSearch"
        >
          <template #left>
            <van-icon name="arrow-left" @click="onBack" />
          </template>
        </van-search>
      </form>
    </div>
    <div class="app-header-search-height"></div>
    <div class="main" v-show="isShow">
      <product-list
        v-if="searchMethod === 'product'"
        ref="productListRef"
        :method="'search'"
        :search-val="searchVal"
        :is-immediate="false"
      />
      <article-list
        v-else
        ref="articleListRef"
        :method="'search'"
        :search-val="searchVal"
        :is-immediate="false"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { SearchInstance } from 'vant'
import ProductList from '../../../components/product-list.vue'
import ArticleList from '../../../components/article-list.vue'

const searchRef = ref<SearchInstance>()
const router = useRouter()
const searchVal = ref<string>('')
const productListRef = ref<InstanceType<typeof ProductList>>()
const articleListRef = ref<InstanceType<typeof ArticleList>>()
const searchMethod = ref<'product' | 'article'>('product')
const isShow = ref<boolean>(false)

const onSearch = () => {
  isShow.value = true
  if (searchMethod.value === 'product') {
    if (!productListRef.value) return
    productListRef.value.refreshing = true
    productListRef.value.onRefresh()
  } else {
    if (!articleListRef.value) return
    articleListRef.value.refreshing = true
    articleListRef.value.onRefresh()
  }
}
const initData = () => {
  searchVal.value = ''
  if (productListRef.value) {
    productListRef.value.list = []
    productListRef.value.finished = false
  }
  if (articleListRef.value) {
    articleListRef.value.list = []
    articleListRef.value.finished = false
  }
}
const onBack = () => {
  router.back()
}
onActivated(() => {
  const beforeRouter = window.history.state.back
  if (beforeRouter === '/found') {
    searchMethod.value = 'article'
  } else {
    searchMethod.value = 'product'
  }
  const forwardRouter = window.history.state.forward
  if (forwardRouter === null) {
    initData()
  }
})
onDeactivated(() => {
  const forwardRouter = window.history.state.forward
  if (forwardRouter !== null) {
    isShow.value = false
  }
})
</script>

<style lang="scss" scoped>
.search {
  height: 100%;
  .header {
    :deep(.van-icon) {
      font-size: 20px;
      margin-right: 7px;
    }
  }
  .main {
    height: 100%;
  }
}
</style>
